﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.ServiceBus.Common
{
    public class General
    {
        public void SendMsg(string message = "Hello, RabbitMQ!")
        {
            var factory = new ConnectionFactory() { HostName = "localhost" }; // 默认端口是 5672
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                // 声明一个队列（如果不存在则创建）
                channel.QueueDeclare(queue: "hello",
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                var body = Encoding.UTF8.GetBytes(message);

                // 发布消息到队列
                channel.BasicPublish(exchange: "",
                                     routingKey: "hello",
                                     basicProperties: null,
                                     body: body);

                Console.WriteLine(" [x] Sent {0}", message);
            }

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }

        public void ConsumeMsg()
        {
            //var factory = new ConnectionFactory()
            //{
            //    HostName = "your-rabbitmq-server.com",
            //    Port = 5672,
            //    UserName = "your-username",
            //    Password = "your-password",
            //    VirtualHost = "/"
            //};

            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                // 声明一个队列（如果不存在则创建）
                channel.QueueDeclare(queue: "hello",
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                // 创建消费者
                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body.ToArray();
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(" [x] Received {0}", message);
                };

                // 开始消费
                channel.BasicConsume(queue: "hello",
                                     autoAck: true,
                                     consumer: consumer);

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
            }
        }

    }
}
